package org.ch02.hw.demo06;

import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ZJL
 * @date 2025-03-17
 */
public class MainTest01 {
    public static void main(String[] args) throws Exception {
        //        六、输入一个合法的Email地址，截取其帐户名。
//        提示：使用字符串对象:substring()、indexOf()访求实现
//        要求：使用反射实现
        System.out.println("输入一个合法的Email地址：");
        Class<Scanner> clazz = Scanner.class;
        Constructor<Scanner> constructor = clazz.getConstructor(InputStream.class);
        Scanner scanner = constructor.newInstance(System.in);
        Method nextLine = clazz.getMethod("nextLine");
        String email = (String) nextLine.invoke(scanner);
        boolean validEmail = isValidEmail(email);
        if (!validEmail) {
            System.out.println("请输入合法的Email地址！！！");
            return;
        }
        Class<String> stringClass = String.class;
        Method indexOf = stringClass.getMethod("indexOf", String.class);
        int index = (int) indexOf.invoke(email, "@");
        Method substring = stringClass.getMethod("substring", int.class, int.class);
        String name = (String) substring.invoke(email,0,index);
        System.out.println(name);
    }

    // 使用正则表达式验证邮箱地址
    public static boolean isValidEmail(String email) {
        // 正则表达式
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        Pattern pattern = Pattern.compile(emailRegex);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}
